package com.mask.example.service;

import com.mask.example.entity.User;
import com.mask.example.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 用户服务示例
 * 展示如何在用户项目中实现业务逻辑
 *
 * @author mask
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    /**
     * 查找所有用户
     */
    public List<User> findAll() {
        return userRepository.findAll();
    }

    /**
     * 根据ID查找用户
     */
    public User findById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + id));
    }

    /**
     * 根据用户名查找用户
     */
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    /**
     * 保存用户
     */
    public User save(User user) {
        // 如果是新用户，加密密码
        if (user.getId() == null && user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        return userRepository.save(user);
    }

    /**
     * 根据ID删除用户
     */
    public void deleteById(Long id) {
        if (!userRepository.existsById(id)) {
            throw new RuntimeException("用户不存在: " + id);
        }
        userRepository.deleteById(id);
    }

    /**
     * 批量删除用户
     */
    public void deleteByIds(List<Long> ids) {
        userRepository.deleteAllById(ids);
    }

    /**
     * 重置用户密码
     */
    public void resetPassword(Long id) {
        User user = findById(id);
        user.setPassword(passwordEncoder.encode("123456")); // 默认密码
        userRepository.save(user);
    }

    /**
     * 切换用户状态
     */
    public void toggleStatus(Long id) {
        User user = findById(id);
        user.setEnabled(!user.isEnabled());
        userRepository.save(user);
    }

    /**
     * 更新用户最后登录时间
     */
    public void updateLastLoginTime(Long id) {
        User user = findById(id);
        user.setLastLoginTime(java.time.LocalDateTime.now());
        userRepository.save(user);
    }
}
